# -*- coding: utf-8 -*- 
"""
@Author : Chan ZiWen
@Date : 2022/8/1 13:02
File Description:

"""
import json
import time
import numpy as np
import pandas as pd

from datetime import datetime, timedelta, date
from flask import request, Blueprint, jsonify
from common.feishu import FeishuMsgHandler
import matplotlib.pyplot as plt

recMob = Blueprint('recMob', __name__)

# 生成公用参数
a, b = 20, 30
c = a + b
filters_before = [1] * a + [0] * b
filters_before = np.array(filters_before)
filters_after = [0] * b + [1] * a
filters_after = np.array(filters_after)

# 记录已经请求的date: ['s,e', 's,e']
dict_requests = {}


def awayGoHome(d1: dict = None, d2: dict = None):
    """ multi-thread processing
    procedure:
        1, creating threads
        2, ordering data by log_time
        3, calling single mac analysis function
        
        
        log_time与res_s的值一一对应
    计算每天全量用户家中有离回家的设备：
        避免识别到笔记本，电脑等不是移动设备（在家办公）：设置 白天（4-11点） 晚上（15-24点）

    通过filter去匹配。
    log_time: [timestamp1, timestamp2, ...] , 表示当前时间是在局域网内, shape of (n,)
    :return:
    """
    # dict to Dataframe
    df_awayHome = pd.DataFrame.from_dict(data=d1, orient='index', columns=['isOnline'])
    df_goHome = pd.DataFrame.from_dict(data=d2, orient='index', columns=['isOnline'])
    res_flag = 0
    # 遍历 出门数据
    awayHome_values = df_awayHome['isOnline'].values
    goHome_values = df_goHome['isOnline'].values

    if len(awayHome_values) >= a:
        # pd.Series(awayHome_values, index=range(len(awayHome_values))).plot()
        # plt.show()
        for i in range(c, len(awayHome_values) - c):
            temp = awayHome_values[(i - c):i]
            x = temp == filters_before
            res1, res2 = np.sum(x[:a]), np.sum(x[a:])
            if res1 <= 7 and res2 == b:
                # print(res, end='  ')
                res_flag += 1
                break
    # 遍历 回家数据
    if len(goHome_values) >= a:
        # pd.Series(goHome_values, index=range(len(goHome_values))).plot()
        # plt.show()
        for i in range(c, len(goHome_values) - c):
            temp = goHome_values[(i - c):i]
            x = temp == filters_after
            res1, res2 = np.sum(x[:b]), np.sum(x[b:])
            if res2 <= 7 and res1 == b:
                # print(res, end='  ')
                res_flag += 1
                break
    return True if res_flag == 2 else False


def gen_seq():
    d1, d2 = {}, {}
    for h in range(4, 12):
        for m in range(0, 60):
            s = f"{h:0>2}{m:0>2}"
            d1[s] = 0
    for h in range(14, 24):
        for m in range(0, 60):
            s = f"{h:0>2}{m:0>2}"
            d2[s] = 0
    return d1, d2


def run(date_q, data_json):
    print(f"Begin of the ({date_q})")
    start = time.time()
    MD_str = ''
    for k_mac, data in data_json.items():
        if len(k_mac) != 12:
            print(f"The mac({k_mac}) is not recognized!")
            continue
        # jsons to list
        d1, d2 = gen_seq()
        for K in data:
            t = int(K[:2])
            if 4 <= t < 12:
                d1[K] = 1
            elif t >= 14:
                d2[K] = 1

        ans = awayGoHome(d1, d2)
        if ans:
            MD_str += (',' + k_mac)
    print(f"Total duration(read & analysis) time: {(time.time() - start) / 60}(m) ")
    return MD_str.strip(',')


@recMob.route('/res', methods=['POST'])
def main():
    """
    http://172.20.146.119:8688/analyze/recMob/res
    """
    if request.json is None:
        json_q = json.loads(request.data)
    else:
        json_q = request.json
    json_q.pop('name')
    date_q = json_q.pop('date')

    try:
        res = run(date_q, json_q)
        return res, 200
        # return jsonify(date=date_q, result=res), 200
    except RuntimeError as e:
        return f'{e}', 404
